/**
 * 统一管理localstorage和cookies的信息
 */

import { useCookie } from '@/@core/composable/useCookie';

// 定义需要同步的键名
const SYNC_KEYS = {
    TOKEN: 'justech-token',
    REFRESH_TOKEN: 'justech-refreshToken',
    USER_INFO: 'justech-userInfo',
};

// 从localStorage同步到cookie
export function syncToCookies() {
    if (typeof window === 'undefined') return; // 确保在浏览器环境执行

    // 同步token
    const tokenStr = localStorage.getItem(SYNC_KEYS.TOKEN);
    if (tokenStr) {
        const tokenData = JSON.parse(tokenStr);
        useCookie('accessToken').value = tokenData.content;
    }

    // 同步用户信息
    const userInfoStr = localStorage.getItem(SYNC_KEYS.USER_INFO);
    if (userInfoStr) {
        const userData = JSON.parse(userInfoStr);
        useCookie('userData').value = userData.content;

        // 设置权限规则
        const abilityRules = [{ action: 'manage', subject: 'all' }];
        useCookie('userAbilityRules').value = abilityRules;
    }
}

// 清除localStorage和cookie中的数据
export function clearStorage() {
    if (typeof window === 'undefined') return; // 确保在浏览器环境执行

    // 清除localStorage
    localStorage.removeItem(SYNC_KEYS.TOKEN);
    localStorage.removeItem(SYNC_KEYS.REFRESH_TOKEN);
    localStorage.removeItem(SYNC_KEYS.USER_INFO);

    // 清除cookies
    useCookie('accessToken').value = null;
    useCookie('userData').value = null;
    useCookie('userAbilityRules').value = null;
}
